package cn.iocoder.yudao.framework.common.util;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * 类CollectionUtil.java的实现描述：集合工具类
 * 
 * @author Bruce 2015年3月25日 下午4:27:48
 */
public class CollectionUtil {

    /**
     * 些方法，会先移除集合中 null 的元素，在做比较.
     * 
     * @param col
     */
    public static <T> boolean isEmpty(Collection<T> col) {
        removeNull(col);
        return CollectionUtils.isEmpty(col);
    }

    /**
     * 移除集合中 null 元素.
     * 
     * @param list
     */
    public static <T> void removeNull(Collection<T> list) {
        if (list == null || list.size() == 0) {
            return;
        }
        Iterator<T> iter = list.iterator();
        while (iter.hasNext()) {
            if (iter.next() == null) {
                iter.remove();
            }
        }

    }

    /**
     * 移除字符串集合中 空（null和空字符串） 元素.
     * 
     * @param list
     */
    public static void removeEmpty(Collection<String> list) {
        if (list == null || list.size() == 0) {
            return;
        }
        Iterator<String> iter = list.iterator();
        while (iter.hasNext()) {
            String next = iter.next();
            if (next == null || next.equals("")) {
                iter.remove();
            }
        }

    }

    /**
     * Answers true if a predicate is true for at least one element of a collection.
     * <p>
     * A <code>null</code> collection or predicate returns false.
     * 
     * @param collection the collection to get the input from, may be null
     * @param predicate the predicate to use, may be null
     * @return true if at least one element of the collection matches the predicate
     */
    @SuppressWarnings("rawtypes")
    public static boolean exists(Collection collection, Predicate predicate) {
        if (collection != null && predicate != null) {
            for (Iterator it = collection.iterator(); it.hasNext();) {
                if (predicate.evaluate(it.next())) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        List<Object> list = new ArrayList<Object>();
//        list.add("aa");
        list.add(null);
        list.add(null);
        System.out.println(list);
        removeNull(list);
        System.out.println(isEmpty(list));
        

    }
}
